/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import styled from 'styled-components';
import i18n from 'i18next';
import { InboxOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { message, Modal, Upload } from 'antd';
import {
  CommandDialog,
  BaseCommand,
  AliOSSInst,
  StringUtils,
} from '@amcax/base';
import { Vector3 } from 'three';
import { createAirFoilLine } from '../cmd-airfoil/cmdAirfoilAPI';
import { clearScene } from '../cmd-airfoil';
import { useState } from 'react';
import { clearLocalListDatas } from '../../widgets/RightNavigation/panels/InputPanel';
import { ctx2, userEvents } from '../../../../module';

const { Dragger } = Upload;

const StyledLayout = styled.div`
  display: flex;
  padding: 10px;
  & .ant-upload-drag {
    width: 400px;
    height: auto;
  }
`;

interface ImportDialogProps {
  title: string;
  onClose: () => void;
}

function ImportDialog({ title, onClose }: ImportDialogProps) {
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [file, setFile] = useState<File>(null);
  let fileType = '';

  const uploadFile = async (options: any) => {
    const { file, onSuccess, onProgress, onError } = options;

    fileType = file.name.split('.')[1];
    const ossfile = StringUtils.randomString(10) + '.' + fileType;
    AliOSSInst.uploadFile(
      'cad',
      ossfile,
      file,
      (p: any) => {
        console.log('uploadProgress:', p);
        onProgress({ percent: Math.round(p * 100).toFixed(2) }, file);
      },
      (data: any) => {
        const path = data.path;
        // 判断场景中是否存在翼型
        if (ctx2.cadScene.edgeGroup.children.length > 0) {
          setFile(file);
          setOpen(true);
        } else {
          doRender(file);
          userEvents.emit('importAirfoil', true);
        }
        onSuccess({ name: path, status: 'done', file });
      },
    );
  };

  const props: UploadProps = {
    name: 'file',
    multiple: true,
    accept: '.txt',

    onChange(info: any) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        console.log(`${info.file.name} 文件上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
    customRequest: uploadFile,
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    },
  };

  const doRender = async (file: File) => {
    if (file) {
      const reader = new FileReader();
      reader.onload = async (e) => {
        const content = JSON.stringify(e.target.result);
        const posList = JSON.parse(content);
        const lines = posList.split('\n');
        const array = lines.map((line) => line.split(', ').map(Number));
        const vertexes = array.map((item) => {
          return new Vector3(item[0], item[1], 0);
        });
        await createAirFoilLine(vertexes);
      };
      reader.readAsText(file);
    }
    userEvents.emit('sceneEmpty', false);
    onClose();
  };

  /**
   * 编辑后 更新翼型提示框
   */
  const handleOk = async () => {
    setConfirmLoading(true);
    await clearScene();
    doRender(file);
    setConfirmLoading(false);
    clearLocalListDatas();
    userEvents.emit('importAirfoil', true);
    onClose();
  };

  const handleCancel = () => {
    setOpen(false);
    onClose();
  };

  return (
    <CommandDialog
      title={title}
      onClose={onClose}
      placement='top'>
      <StyledLayout>
        <Dragger {...props}>
          <p className='ant-upload-drag-icon'>
            <InboxOutlined />
          </p>
          <p className='ant-upload-text'>{i18n.t('uploader.drag_text')}</p>
          <p className='ant-upload-hint'>
            {'支持上传的文件类型：翼型点列表.txt'}
          </p>
        </Dragger>
      </StyledLayout>
      <Modal
        title='修改提示'
        open={open}
        onCancel={handleCancel}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        okText='继续'
        cancelText='取消'
        style={{ borderRadius: '10px' }}>
        <p>场景中已有翼型数据，导入翼型将清除之前数据，是否继续？</p>
      </Modal>
    </CommandDialog>
  );
}

export const cmdImport: BaseCommand = {
  id: 'CmdImport',
  label: '导入',
  icon: 'commands/airfoil/import',
  noHighlight: true,

  create: (label: string, onClose: () => void) => (
    <ImportDialog
      title={i18n.t(label)}
      onClose={onClose}
    />
  ),
};
